//
//  QBNewFeatureViewController.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/23.
//  Copyright © 2016年 bing. All rights reserved.


import UIKit

private let reuseIdentifier = "Cell"

class QBNewFeatureViewController: UICollectionViewController {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 流水布局
    let layout = UICollectionViewFlowLayout()
    
    // 因为父类没有init()这构造函数，子类不需要使用overrider
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        // 设置layout的参数
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
        // 注册
        collectionView?.registerClass(QBNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
}

// MARK: - collectionView数据源方法和代理方法
extension QBNewFeatureViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return QBNewFeaturePageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! QBNewFeatureCell
        
        cell.backgroundColor = UIColor.random()
        
        // 设置cell要显示的页码
        cell.index = indexPath.item
        
        //cell.startButtonAnimation()
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        // 计算当前页
        let page = Int(scrollView.contentOffset.x / UIScreen.mainScreen().bounds.width)
        
        //print("page:\(page)")
        
        // 判断当前是否是最后一页
        if page == QBNewFeaturePageCount - 1 {
            
            let indexPath = NSIndexPath(forItem: page, inSection: 0)
            let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! QBNewFeatureCell
            
            // 让开始动画
            cell.startButtonAnimation()
        }
    }
}

// 自定义的cell
class QBNewFeatureCell: UICollectionViewCell {
    
    // MARK: - 属性
    /// 当前显示的页数
    var index: Int = 0 {
        didSet {
            
            bkgImageView.image = UIImage(named: "new_feature_\(index + 1)")
            
            // 只要cell要设置背景图片，按钮就隐藏
            startButton.hidden = true
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }
    
    // MARK: - 按钮点击事件
    func didClickStartButton() {
        // 切换到QBMainViewController
//        let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//        
//        appDelegate?.window?.rootViewController = QBMainViewController()
        
        AppDelegate.outSwitchRootViewController(QBMainViewController())
    }
    
    // 开始按钮动画
    func startButtonAnimation() {
        
        startButton.hidden = false
         // 在开始动画之前,将transform Scale设置为0
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }, completion: nil)
    }
    
    private  func prepareUI() {
        
        // 1.添加子控件, 注意往contentView里面添加
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        
        // 2.添加约束
        bkgImageView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 背景
        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        // 开始按钮
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
    }
    
    // MARK: - 懒加载
    /// 背景
    private lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    
    private lazy var startButton: UIButton = {
        let button = UIButton()
        
        // 设置按钮
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "didClickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
